package org.tinyweb.core;

import org.tinyweb.config.TinyWebConfig;
import org.tinyweb.render.RenderFactory;

import javax.servlet.ServletContext;

/**
 * Created by beyond on 2014/10/24.
 */
public class TinyWeb {

    private static final TinyWeb tinyWeb = new TinyWeb();
    private Config config;

    private ServletContext servletContext;
    private Handler handler;
    private RenderFactory renderFactory;
    private Path path;

    private TinyWeb(){

    }

    public static TinyWeb instance(){
        return tinyWeb;
    }

    boolean init(TinyWebConfig tinyWebConfig,ServletContext servletContext){
        this.servletContext = servletContext;
        config = new Config();
        tinyWebConfig.init(config);
        initPath(servletContext);
        initHandle(config.getStartupsPackage(),config.getRootPackage(),config.getEncoding());
        initRender(config.getEncoding(),config.getViewType());
        return true;
    }

    /**
     * 初始化处理器
     * @param startupPackage
     * @param rootPackage
     */
    private void initHandle(String startupPackage,String rootPackage,String encoding){
        handler = Handler.instance();
        handler.init(startupPackage, rootPackage,encoding);
    }

    /**
     * 初始化渲染器
     * @param encoding
     * @param viewType
     */
    private void initRender(String encoding,String viewType){
        renderFactory = RenderFactory.instance();
        renderFactory.init(encoding,viewType);
    }

    /**
     * 初始化路径服务
     * @param servletContext
     */
    private void initPath(ServletContext servletContext){
        path = Path.instance();
        path.init(servletContext);
    }

    public ServletContext getServletContext() {
        return servletContext;
    }

    public Handler getHandler() {
        return handler;
    }

    public RenderFactory getRenderFactory() {
        return renderFactory;
    }

    public Path getPath() {
        return path;
    }
}
